using System;
using System.Collections.Generic;
using System.Windows.Browser;
namespace HtmlUtilities
{
    public static class ScriptObjectFactory
    {
        private static readonly Dictionary<ScriptObject, IScriptObject> _wrappers = new Dictionary<ScriptObject, IScriptObject>();
        public static IScriptObject GetScriptObject(ScriptObject source)
        {
            if(source == null)
                return null;

            if (_wrappers.ContainsKey(source))
                return _wrappers[source];

            var wrapper =  CreateWrapper(source);
            _wrappers.Add(source, wrapper);

            return wrapper;
        }

        public static T GetScriptObject<T>(ScriptObject source) where T : IScriptObject
        {
            return (T)GetScriptObject(source);
        }

        private static IScriptObject CreateWrapper(ScriptObject source)
        {
            if (source is HtmlElement)
                return new HtmlElementWrapper(source as HtmlElement);

            if (source is HtmlDocument)
                return new HtmlDocumentWrapper(source as HtmlDocument);

            if (source is HtmlWindow)
                return new HtmlWindowWrapper(source as HtmlWindow);

            if (source is HtmlObject)
                return new HtmlObjectWrapper(source as HtmlObject);

            if (source is ScriptObjectCollection)
                return new ScriptObjectCollectionWrapper(source as ScriptObjectCollection);

            return new ScriptObjectWrapper(source);
        }
    }
}